import React, { PureComponent, Fragment } from "react";
import ReactDom from 'react-dom';
import { DatePickerView, Modal, Button, PickerView } from "antd-mobile";
import { isNull, combineDefaultStr, handleDateFunc, timeZero, timeMsec } from "../../../utils/helper"
import moment from "moment"
import { MIcon } from "../../MIcon";
interface Props {
	value: any,
	value_datatype?: string,
	type?: any,
	is_msec?: any,
	onChange: Function,
	is_now?: any,
	show_format?: string,
	format?: string,
	[k: string]: any
}
interface State {
	value: any,
	datePickerValue: any,
	showModal: boolean
}
const province = [
	{
		label: '2019年',
		value: '2019',
		children: [
			{
				label: '12月',
				value: '12',
				children: [
					{
						label: '29日',
						value: 1577577600,
					}
				]
			}
		],
	},
	{
		label: '2020年',
		value: '2020',
		children: [
			{
				label: '1月',
				value: '1',
				children: [

					{
						label: '12日',
						value: 1578787200,
					},
					{
						label: '15日',
						value: 1579046400,
					},
				],
			},
			{
				label: '2月',
				value: '2',
				children: [
					{
						label: '1日',
						value: 1580515200,
					},
					{
						label: '29日',
						value: 1582934400,
					},
				],
			},
			{
				label: '3月',
				value: '3',
				children: [
					{
						label: '1日',
						value: 1583020800,
					},
					{
						label: '29日',
						value: 1585440000,
					},
				],
			},
		],
	},
];
export default class MyDatePickerClickData extends PureComponent<Props, State> {
	timer = null;
	public state: State = {
		value: this.props.value,
		datePickerValue: null,
		showModal: false
	}
	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			let { value } = nextProps;
			if (isNull(value)) {
				if (value === undefined) {
					let { is_now, value_datatype = "string" } = nextProps;
					let isNumber = value_datatype === "number";

				}
			}
			else {
				if (value.toString().indexOf("get") != -1) {
					value = moment(handleDateFunc(value));
					this.changeValue(moment(value))
				}
			}
			this.setState({
				value
			});
		}
	}
	changeValue = (value) => {
		if (!value._isAMomentObject) {
			value = moment(value);
		}
		const { value_datatype = "string", type = "date", is_msec = 0 } = this.props;
		let isNumber = value_datatype === "number";
		let mFormat = "YYYY-MM-DD";
		if (isNull(value)) {

		}
		else {
			if (type == "month") {
				mFormat = "YYYY-MM-01"
			}
			else if (type == "year") {
				mFormat = "YYYY-01-01"
			}
			if (isNumber) {
				value = timeZero(value);
				// value = parseInt(value.valueOf() / 1000)
				value = Number(value.valueOf() / timeMsec(is_msec))
			}
			else {
				value = timeZero(value);
				value = value.format(mFormat)
			}
		}
		this.setState({
			value: value
		});
		clearTimeout(this.timer);
		this.timer = setTimeout(() => {
			if (!('value' in this.props)) {
				this.setState({
					value: value
				});
			}
			this.triggerChange(value);
		}, 300)
	};

	triggerChange = (changedValue) => {
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(changedValue);
		}
	};
	onChange = (value) => {
		value = moment(value);
		this.changeValue(value);
	};

	componentDidMount() {
		let { is_now = 0, value_datatype = "string" } = this.props;
		let { value } = this.state;
		let isNumber = value_datatype === "number";
		if (isNull(value)) {

		}
		else {
			if (value.toString().indexOf("get") != -1) {
				value = moment(handleDateFunc(value));
				this.changeValue(moment(value))
			}
		}
	}
	toggleModal = () => {
		let { showModal, value } = this.state;
		this.setState({
			showModal: !showModal
		})
	}
	renderButton() {
		let { value } = this.state;
		let { value_datatype = "string", is_msec = 0, show_format, list, type = "date" } = this.props;
		let showValue = "请选择日期";
		if (!isNull(value)) {
			if (value_datatype == "number") {
				if (is_msec == 1) {

				}
				else {
					value = value * 1000
				}
			}
			else {
				value = value.replace(/-/g, "/");
			}
			if (isNull(show_format)) {
				if (type == "date") {
					show_format = "YYYY年MM月DD日"
				}
				else if (type == "month") {
					show_format = "YYYY年MM月"
				}
				else if (type == "year") {
					show_format = "YYYY年"
				}
			}
			showValue = moment(value).format(show_format)
		}
		let strFormat = "YYYY-MM-DD";
		if (type == "month") {
			strFormat = "YYYY-MM-01"
		}
		if (type == "year") {
			strFormat = "YYYY-01-01"
		}
		let currentvalueStr = moment(value).format(strFormat);
		let len = list.length;
		let isFirst = false;
		let isEnd = false;
		if (list && list.length > 0) {
			if (list[0].value == currentvalueStr) {
				isFirst = true
			}
			if (list[len - 1].value == currentvalueStr) {
				isEnd = true
			}
		}

		return (
			<div data-flex="box:mean cross:center" style={{ width: "100%" }}>
				{
					isFirst ? <div></div> : <div style={{ textAlign: "center" }} onClick={() => {
						this.prevNextDate("prev")
					}} >
						<MIcon type="left" style={{ fontSize: "30px", color: "#999" }} />
					</div>
				}
				<div onClick={() => {
					let day = value;
					if (value_datatype == "string") {
						day = new Date(value).getTime() / 1000
					}
					else {
						day = value / 1000
					}
					let newVal = [moment(day * 1000).startOf("year").valueOf() / 1000, moment(day * 1000).startOf("month").valueOf() / 1000, day];
					console.log("newVal", newVal);
					this.setState({
						datePickerValue: newVal
					})
					this.toggleModal();
				}} style={{ textAlign: "center", width: "50%", margin: "0 5%", height: "40px", lineHeight: "38px" }}>
					{showValue}
				</div>
				{
					isEnd ? <div></div> : <div style={{ textAlign: "center" }} onClick={() => {
						this.prevNextDate("next")
					}} >
						<MIcon type="xiayiye" style={{ fontSize: "30px", color: "#999" }} />
					</div>
				}
			</div>
		)
	}
	prevNextDate = (str) => {
		let { type = "date" } = this.props;
		let num = 1;
		if (str == "prev") {
			num = -1
		}
		else if (str == "next") {
			num = 1
		}
		let { value } = this.state;
		let { value_datatype = "string", is_msec = 0, list } = this.props;

		if (value_datatype === "number") {
			if (is_msec == 1) {

			}
			else {
				let format = "YYYY-MM-DD";
				if (type == "month") {
					format = "YYYY-MM-01"
				}
				if (type == "year") {
					format = "YYYY-01-01"
				}
				value = moment(value * 1000).format(format)
			}
		}
		// string   2020-03-24  number  1584979200000
		// 求当前时间deindex
		let index = -1;
		let len = list.length;
		for (let i = 0; i < len; i++) {
			if (value == list[i].value) {
				index = i;
				break;
			}
		}
		let newValue = list[index + num].value;//2020-03-12
		newValue = moment(newValue).valueOf();
		this.changeValue(newValue);
	}
	listToDateTree = (arr) => {//转成三级下拉所需的树形结构
		let newArr = [];
		arr.map(i => {
			let { value } = i;
			let valueArr = value.split("-");
			value = new Date(value.replace("-", "/")).getTime() / 1000;
			let [year, month, day] = valueArr;
			let yearCount = newArr.filter(y => moment(y.value * 1000).format("YYYY") == year).length;
			if (yearCount == 0) { //还没有这个年份
				newArr.push({
					value: moment(value * 1000).startOf("year").valueOf() / 1000,//年第一天 的时间戳
					label: year + "年",
					children: [{
						value: moment(value * 1000).startOf("month").valueOf() / 1000,//月第一天 的时间戳,
						label: month + "月",
						children: [{
							value: value,
							label: day + "日"
						}]
					}]
				})
			} else { //有这个年份了
				newArr = newArr.map(item => {
					if (moment(item.value * 1000).format("YYYY") == year) {
						let { children } = item;
						let monthCount = children.filter(m => moment(m.value * 1000).format("MM") == month).length;
						if (monthCount == 0) { //还没有这个月份
							item = {
								...item,
								children: [
									...item.children,
									{
										value: moment(value * 1000).startOf("month").valueOf() / 1000,
										label: month + "月",
										children: [{
											value: value,
											label: day + "日"
										}]
									}
								]
							}
						} else { //有这个月份了
							children = children.map(c => {
								if (moment(c.value * 1000).format("MM") == month) {
									let { children: days } = c;
									let dayCount = days.filter(d => moment(d.value * 1000).format("DD") == day).length;
									if (dayCount == 0) { //没有这个日
										return {
											...c,
											children: [
												...c.children,
												{
													value: value,
													label: day + "日"
												}
											]
										}
									}
								}
								else {
									return {
										...c
									}
								}
							})
							item = {
								...item,
								children
							}
						}
						return {
							...item
						}
					} else {
						return {
							...item
						}
					}
				})
			}
		})
		return newArr;
	}

	render() {
		let { type = "date", value_datatype = "string", format, fd, dataset_key, dispatch, list, formDataKey, setFieldsValue, field } = this.props;
		let { datePickerValue, showModal, value } = this.state;
		let loading = fd[dataset_key + "Loading"];
		let oldVal = value;
		let isNumber = value_datatype === "number";
		let isString = value_datatype === "string";
		// 数据源加载完成之后
		if (loading === false) {
			if (!isNull(oldVal)) {
				dispatch({
					type: "form/setStateFd",
					payload: {
						formDataKey,
						value: {
							[dataset_key + "Loading"]: undefined
						}
					}
				});
			}
			else {
				if (oldVal === undefined) {
					let newVal = list[list.length - 1].value;
					if (isNumber) {
						newVal = new Date(newVal.replace("-", "/")).getTime() / 1000
					}
					setFieldsValue({
						[field[0]]: newVal
					});
				}
				dispatch({
					type: "form/setStateFd",
					payload: {
						formDataKey,
						value: {
							[dataset_key + "Loading"]: undefined
						}
					}
				})
			}
		}

		if (isNull(value)) {

		}
		else {
			if (isString) {
				value = new Date(value.replace(/-/g, "/")).getTime() / 1000
			}
		}
		let cols = 3;
		if (type == "month") {
			cols = 2
		}
		else if (type == "year") {
			cols = 1
		}
		return (
			<div className="am-list-item" style={{ paddingLeft: 0, lineHeight: "unset" }}>
				{this.renderButton()}
				<Modal
					visible={showModal}
					transparent
					wrapClassName="datepicker"
					style={{ width: "80%" }}
					footer1={
						[
							{
								text: "取消", onPress: () => {

								}
							},
							{
								text: "确定", onPress: () => {

								}
							}
						]
					}
				>
					<div className="am-picker-popup-header" >
						<div className="am-picker-popup-item am-picker-popup-header-left" onClick={() => {
							this.toggleModal()
						}}>取消</div>
						<div className="am-picker-popup-item am-picker-popup-title">选择时间</div>
						<div className="am-picker-popup-item am-picker-popup-header-right" onClick={() => {
							let _index = 2;
							if (type == "month") {
								_index = 1
							}
							if (type == "year") {
								_index = 0
							}
							this.changeValue(datePickerValue[_index] * 1000)
							this.toggleModal();
						}}>确定</div>
					</div>
					<PickerView
						value={datePickerValue}
						data={this.listToDateTree(list)}
						cols={cols}
						onChange={e => {
							console.log("onChange", e);
							this.setState({
								datePickerValue: e
							})
						}}
					/>
				</Modal>

			</div>
		)
	}
}
/*
数据源返回格式,时间从小到大排序
type:date时返回
[
	{value:"2012-02-02"},
	{value:"2012-02-03"},
	{value:"2012-02-04"},
	{value:"2012-02-05"},
	{value:"2012-03-02"},
	{value:"2012-03-15"},
	{value:"2012-03-21"},
	{value:"2012-04-02"},
	{value:"2012-04-05"},
	{value:"2012-04-09"},
]
type:month时返回
[
	{value:"2012-02"},
	{value:"2012-03"},
	{value:"2013-03"}
]
type:year时返回
[
	{value:"2012"},
	{value:"2013"}
]
*/